package com.neuedu.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.neuedu.config.NeueduException;
import com.neuedu.entity.Customer;
import com.neuedu.mapper.CustomerMapper;
import com.neuedu.service.CustomerService;
import com.neuedu.util.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 用户表 服务层实现。
 *
 * @author Administrator
 * @since 2024-06-03
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Resource
    PasswordEncoder passwordEncoder;
    @Override
    public boolean add(String username, String password) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", username);
        if (this.count(wrapper) > 0) {
            throw new NeueduException("手机号已经存在");
        }
        return this.save(new Customer(username, passwordEncoder.encode(password), Date.valueOf(LocalDate.now())));
    }

    @Override
    public String login(String username, String password) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", username);
        Customer customer = this.getOne(wrapper);
        if (null == customer || !passwordEncoder.matches(password, customer.getPassword())) {
            throw new NeueduException("用户名或密码错误");
        }
        if (!customer.getActive()) {
            throw new NeueduException("该用户已经禁用");
        }
        this.updateById(new Customer(customer.getId(), new Date(System.currentTimeMillis())));
        return JwtUtil.getToken(customer);
    }
}
